package com.lengyu.vxminiprogram.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lengyu.vxminiprogram.common.AuthUtil;
import com.lengyu.vxminiprogram.common.BasePageParamDto;
import com.lengyu.vxminiprogram.common.CommonUtils;
import com.lengyu.vxminiprogram.common.HttpResultDto;
import com.lengyu.vxminiprogram.convert.IWorkOrderViewConverter;
import com.lengyu.vxminiprogram.dto.WorkOrderDto;
import com.lengyu.vxminiprogram.dto.WorkOrderRequestDto;
import com.lengyu.vxminiprogram.entity.*;
import com.lengyu.vxminiprogram.security.rest.dto.JwtUser;
import com.lengyu.vxminiprogram.service.*;
import com.lengyu.vxminiprogram.vx.miniprogram.service.IVxApiService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liuyu
 * @since 2024-11-28
 */
@RestController
@RequestMapping("/work-order")
public class WorkOrderController {
    private final static Logger logger = LoggerFactory.getLogger(WorkOrderController.class);
    @Autowired
    IWorkOrderService workOrderService;
    @Autowired
    IWorkOrderUserService workOrderUserService;

    @Autowired
    IWorkOrderProcService workOrderProcService;

    @Autowired
    IWorkOrderViewService workOrderViewService;


    @Autowired
    IWorkOrderViewConverter workOrderViewConverter;

    @Autowired
    IWorkOrderProcViewService workOrderProcViewService;

    @Autowired
    IWorkOrderUserViewService workOrderUserViewService;

    @Autowired
    IVxApiService vxApiService;

    @PostMapping(value="/save")
    public HttpResultDto<String> save(@RequestBody WorkOrderRequestDto workOrderDto){
        if(StringUtils.isBlank(workOrderDto.getWorkOrder().getId())){
            workOrderDto.getWorkOrder().setCurrentStatus("待处理");
            workOrderService.saveOrUpdate(workOrderDto.getWorkOrder());
            workOrderDto.getWorkOrderUserList().forEach(i->{
                i.setWorkOrderId(workOrderDto.getWorkOrder().getId());
            });
            workOrderUserService.saveBatch(workOrderDto.getWorkOrderUserList());
        }
        else{
//            WorkOrder bakWorkOrder = workOrderService.getById(workOrderDto.getWorkOrder().getId());
            workOrderService.saveOrUpdate(workOrderDto.getWorkOrder());
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("work_order_id",workOrderDto.getWorkOrder().getId());
            workOrderUserService.remove(queryWrapper);
            workOrderUserService.saveBatch(workOrderDto.getWorkOrderUserList());

        }
        if(workOrderDto.getWorkOrderUserList() != null && workOrderDto.getWorkOrderUserList().size() > 0){
            workOrderDto.getWorkOrderUserList().forEach(i->{
                vxApiService.sendSubscribeMessage(workOrderDto.getWorkOrder().getTitle(),workOrderDto.getWorkOrder().getInstruction(),
                        CommonUtils.timeToStrYMDHMS(workOrderDto.getWorkOrder().getDeadlineDate().getTime()),
                            i.getUserVxOpenId());
            });
        }


        return HttpResultDto.success();
    }

    /**
     * 批量导入文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload-file")
    public HttpResultDto<String> uploadFile(@RequestPart("file") MultipartFile file){
        JwtUser currentUser = AuthUtil.getCurrentJwtUser();
        if(currentUser == null){
            return HttpResultDto.failed("无权限");
        }
        //判断文件是否为空
        if(file.isEmpty()){
            return HttpResultDto.failed("文件不能为空");
        }
        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();

            // 获取文件的字节
            byte[] bytes = file.getBytes();

            // 这里可以添加保存文件的代码，例如将文件保存到磁盘或数据库
            // 保存文件到本地的路径
            String savePath = "/lengyu/nginx/html/download/work_order/order_img/" + fileName;
            // 保存文件
            file.transferTo(Paths.get(savePath).toFile());
            String avatarUrl = "https://visitor.bjkangdeli.com:12812/download/work_order/order_img/"+fileName;
            return HttpResultDto.success(avatarUrl);
        } catch (Exception e) {
            return HttpResultDto.failed(e.getMessage());
        }
    }

    @PostMapping(value="/page")
    public HttpResultDto<Page<WorkOrderDto>> page(@RequestBody BasePageParamDto pageParamDto){
        //0:所有  1：我发起的  2：我参与的
        int searchType = 0;

        QueryWrapper queryWrapper = new QueryWrapper();
        if(pageParamDto.getParamMapObj() != null){
            for(String key:pageParamDto.getParamMapObj().keySet()){
                if(StringUtils.isNotBlank(String.valueOf(pageParamDto.getParamMapObj().get(key)))){
                    if(key.equals("searchType")){
                        searchType = pageParamDto.getParamMapObj().getInteger(key);
                    }
                    else{
                        queryWrapper.like(key,pageParamDto.getParamMapObj().get(key));
                    }

                }
            }
        }
        if(searchType == 1 ){
            queryWrapper.eq("user_id", AuthUtil.getCurrentJwtUser().getId());
        }
        else if(searchType == 2){
             queryWrapper.like("proc_user_ids", AuthUtil.getCurrentJwtUser().getId());
         }

        logger.info(JSONObject.toJSONString(queryWrapper));
        queryWrapper.orderByDesc("create_time");
        Page<WorkOrderView> entityPage = workOrderViewService.page(new Page<>(pageParamDto.getPageIndex(), pageParamDto.getPageSize()),queryWrapper);
        Page<WorkOrderDto> dtoPage = workOrderViewConverter.pageEntityToDto(entityPage);
        if(dtoPage.getRecords() != null && dtoPage.getRecords().size() > 0){
            dtoPage.getRecords().forEach(i->{
                QueryWrapper queryWrapper1 = new QueryWrapper();
                queryWrapper1.eq("work_order_id",i.getId());
                List<WorkOrderUserView> userList =  workOrderUserViewService.list(queryWrapper1);
                i.setWorkOrderUserList(userList);
            });
        }
        return HttpResultDto.success(dtoPage);

    }

    @GetMapping(value="/detail")
    public HttpResultDto<WorkOrderDto> detail(String id){
        WorkOrderView workOrderView = workOrderViewService.getById(id);
        logger.info(JSONObject.toJSONString(workOrderView));
        WorkOrderDto workOrderDto = workOrderViewConverter.entityToDto(workOrderView);

        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("work_order_id",workOrderDto.getId());
        List<WorkOrderUserView> userList =  workOrderUserViewService.list(queryWrapper1);
        workOrderDto.setWorkOrderUserList(userList);

        queryWrapper1.orderByAsc("create_time");
        List<WorkOrderProcView> procList =  workOrderProcViewService.list(queryWrapper1);
        workOrderDto.setProcList(procList);

        return HttpResultDto.success(workOrderDto);
    }

    @PostMapping(value="/getChartData")
    public HttpResultDto<JSONObject> getChartData(){
        QueryWrapper<WorkOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("order_type as name,count(1) as count");
        queryWrapper.groupBy("order_type");

        List<Map<String, Object>>  countList1 = workOrderService.listMaps(queryWrapper);

        queryWrapper = new QueryWrapper<>();
        queryWrapper.select("current_status as name,count(1) as count");
        queryWrapper.groupBy("current_status");

        List<Map<String, Object>>  countList2 = workOrderService.listMaps(queryWrapper);


        queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("current_status","关闭");
        queryWrapper.ge("deadline_date",CommonUtils.getTodayZeroDate());
        int  noOverlineCount= workOrderService.count(queryWrapper);

        queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("current_status","关闭");
        queryWrapper.le("deadline_date",CommonUtils.getTodayZeroDate());

        int overlineCount =  workOrderService.count(queryWrapper);

        JSONArray overList= new JSONArray();
        JSONObject json1 = new JSONObject();
        json1.put("name","已超时");
        json1.put("count",overlineCount);

        JSONObject json2 = new JSONObject();
        json2.put("name","未超时");
        json2.put("count",noOverlineCount);

        overList.add(json1);
        overList.add(json2);

        JSONObject returnJson = new JSONObject();
        returnJson.put("chartType",countList1);
        returnJson.put("chartStatus",countList2);
        returnJson.put("chartOverline",overList);

        return  HttpResultDto.success(returnJson);
    }
}
